package com.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.entity.ProcessConfig;
import com.common.core.domain.entity.SysUser;
import com.common.core.domain.model.LoginUser;
import com.common.core.page.PageDomain;
import com.common.core.service.ProcessConfigService;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.domain.entity.AllName;
import com.domain.entity.BusinessCount;
import com.flowable.domain.dto.FlowTaskDto;
import com.flowable.domain.vo.FlowQueryVo;
import com.flowable.service.IFlowTaskService;
import com.mapper.HomePageMapper;
import com.project.domain.entity.SyntProject;
import com.service.IHomePageService;
import com.system.domain.SysNotice;
import com.system.mapper.SysNoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomePageServiceImpl implements IHomePageService {

    @Autowired
    private HomePageMapper baseMapper;

    @Autowired
    private SysNoticeMapper noticeMapper;

    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private ProcessConfigService processService;


    @Override
    public List<SysNotice> getNoticeList(SysNotice notice) {
        return noticeMapper.selectNoticeList(notice);
    }

    @Override
    public List<AllName> needTodoList(AllName all) {
        all.setUserId(SecurityUtils.getUserId().toString());

        List<AllName> needTodeList = baseMapper.getTodoList(all);
        dealFlowTask(needTodeList);
        return needTodeList;
    }

    @Override
    public List<AllName> finishedList(AllName all) {
        all.setUserId(SecurityUtils.getUserId().toString());
        List<AllName> finishedList = baseMapper.getDoneList(all);
        dealFlowTask(finishedList);
        return finishedList;
    }

    void dealFlowTask(List<AllName> list) {
        if (list == null || list.size() == 0) return;
        list.forEach(e -> {
            String businessName = e.getBusinessName();
            String largeModule = e.getLargeModule();
            String moduleName = e.getModuleName();
            String projectId = e.getProjectId();
            String businessId = e.getBusinessId();

            //如果businessName那么为空,就去要去v_project中查询businessName  经费模块
            if (StringUtils.isEmpty(businessName) && StringUtils.isNotEmpty(projectId)) {
                SyntProject feePro = baseMapper.getProjectByProjectId(projectId);
                if (feePro != null) {
                    e.setBusinessName(feePro.getName());
                }
            }

            //如果largeModule是项目,还要返回项目id和项目类型   项目模块
            if (StringUtils.isNotEmpty(largeModule) && "项目".equals(largeModule)) {
                if ("出账合同签订".equals(moduleName) || "项目变更".equals(moduleName) || "项目中检".equals(moduleName) || "项目结项".equals(moduleName) || "申报项目".equals(moduleName)) {
                    SyntProject projectSub = baseMapper.getProjectByProjectId(projectId);
                    if (projectSub != null) e.setProjectType(projectSub.getProjectClass());
                } else {
                    SyntProject project = baseMapper.getProjectByProjectId(businessId);
                    if (project != null) {
                        e.setProjectId(project.getId());
                        e.setProjectType(project.getProjectClass());
                    }
                }
            }

            //如果largeModule是经费,会有两个适配的字段要填充,id和checkstatus
            if (StringUtils.isNotEmpty(largeModule) && "经费".equals(largeModule)) {
                e.setId(e.getBusinessId());
                e.setCheckstatus(e.getStatus());
            }

            //如果largeModule是成果,projectType需要根据情况填充
            if (StringUtils.isNotEmpty(largeModule) && "成果".equals(largeModule)) {
                String productType = "";
                switch (moduleName) {
                    case "新品种":
                        productType = "breed";
                        break;
                    case "主办会议":
                        productType = "meeting";
                        break;
                    case "学术讲座":
                        productType = "lecture";
                        break;
                    case "参加会议":
                        productType = "joinMeeting";
                        break;
                    case "人员派遣":
                        productType = "personnelDispatch";
                        break;
                    case "人员接受":
                        productType = "personnelAccept";
                        break;
                    case "论文收录补录":
                        productType = "paperEmbody";
                        break;
                    case "科研成果转化":
                        productType = "transform";
                        break;
                    case "申报获奖":
                        productType = "honorApplyBook";
                        break;
                    default:
                        productType = baseMapper.getAchieveByAchieveId(businessId);
                        break;
                }
                e.setProjectType(productType);
            }
        });
    }


    @Override
    public List<Map<String, String>> handleCount() {
        List<String> moduleList = new ArrayList<>();
        moduleList.add("项目");
        moduleList.add("经费");
        moduleList.add("成果");
        //已办列表
        List<Map<String, String>> doneNum = baseMapper.getDoneNum(SecurityUtils.getUserId().toString(), moduleList);
        //待办列表
        List<Map<String, String>> todoNum = baseMapper.getTodoNum(SecurityUtils.getUserId().toString(), moduleList);

        // 将结果转为 Map 便于查缺补全
        Map<String, Map<String, String>> doneMap = doneNum.stream()
                .collect(Collectors.toMap(m -> m.get("modelName"), m -> m, (v1, v2) -> v1));
        Map<String, Map<String, String>> todoMap = todoNum.stream()
                .collect(Collectors.toMap(m -> m.get("modelName"), m -> m, (v1, v2) -> v1));

        // 补全缺失模块
        for (String module : moduleList) {
            if (!doneMap.containsKey(module)) {
                Map<String, String> map = new HashMap<>();
                map.put("type", "已办");
                map.put("modelName", module);
                map.put("num", "0");
                doneNum.add(map);
            }
            if (!todoMap.containsKey(module)) {
                Map<String, String> map = new HashMap<>();
                map.put("type", "待办");
                map.put("modelName", module);
                map.put("num", "0");
                todoNum.add(map);
            }
        }

        // 合并结果
        List<Map<String, String>> list = new ArrayList<>();
        list.addAll(doneNum);
        list.addAll(todoNum);

        return list;
    }

    @Override
    public List<AllName> processSchedule(AllName all) {
        all.setUserId(SecurityUtils.getUserId().toString());
        List<AllName> allNames = baseMapper.myProcess_sql(all);
        dealFlowTask(allNames);
        return allNames;
    }

    @Override
    public AjaxResult processSchedule2(PageDomain pageDomain) {
        FlowQueryVo query = new FlowQueryVo();
        query.setPageNum(pageDomain.getPageNum());
        query.setPageSize(pageDomain.getPageSize());
        AjaxResult ajaxResult = flowTaskService.myProcess(query);
        Page<FlowTaskDto> page = (Page) ajaxResult.get("data");
        List<FlowTaskDto> records = page.getRecords();
        List<Map<String, String>> list = new ArrayList<>();
        for (FlowTaskDto ft : records) {
            Integer status = ft.getStatus();
            String procDefKey = ft.getProcDefKey();
            ProcessConfig proCig = processService.getProcessByProKey(procDefKey);
            if (proCig == null) continue;
            String moduleName = proCig.getModuleName();
            Map<String, String> map_search = new HashMap<>();
            //流程实例id
            map_search.put("processInstanceId", ft.getProcInsId());
            map_search.put("tableName", "all_name");
            AllName neeTodo = baseMapper.getBusinessByProCig(map_search);
            if (neeTodo == null) continue;
            Map<String, String> map = new HashMap<>();
            map.put("businessId", neeTodo.getBusinessId());
            map.put("businessName", neeTodo.getBusinessName());
            map.put("largeModule", proCig.getLargeModule());
            map.put("moduleName", moduleName);
            map.put("status", String.valueOf(status));
            //关于项目的需要额外的projectType参数
            if (StringUtils.isNotEmpty(moduleName) && (moduleName.equals("进账合同签订") || moduleName.contains("项目"))) {
                map.put("projectType", baseMapper.getProjectTypeFromView(neeTodo.getBusinessId()));
            }

            list.add(map);
        }
        return AjaxResult.success(list);
    }

    @Override
    public List<String> getLargeModules() {
        return baseMapper.getLargeModules();
    }

    public List<BusinessCount> businessCount_fee() {
        //立项金额
        List<BusinessCount> feeList = baseMapper.feeAuthorizeCount();
        List<String> unitIdList = new ArrayList<>();
        feeList.forEach(e -> {
            unitIdList.add(e.getUnitId());
        });

        //到账金额
        List<BusinessCount> incomeFeeList = baseMapper.incomeFeeCount(unitIdList);

        for (BusinessCount fee : feeList) {
            Double incomeFee = 0.0;
            for (BusinessCount income : incomeFeeList) {
                if (fee.getUnitId().equals(income.getUnitId()) && income.getIncomeFee() != null) {
                    incomeFee = income.getIncomeFee();
                    break;
                }
            }
            fee.setIncomeFee(incomeFee);
        }
        return feeList;
    }

    public List<Map<String, Integer>> businessCount_projectNum() {
        String userRealId = null;
        String unitIds = null;
        List<String> list = null;
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kyry".equals(currentRoleKey)) { //统计的是自己负责和参与的项目数量
            userRealId = SecurityUtils.getUserRealId();
        } else if ("biz_kyms".equals(currentRoleKey)) { //统计的是所属单位是自己管理单位的项目数量
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            unitIds = user.getUnitAdminScopeReal();
            if (StringUtils.isNotEmpty(unitIds)) list = Arrays.asList(unitIds.split(","));

        }
        List<Map<String, Integer>> maps = baseMapper.projectNumCount(userRealId, list);
        return maps;
    }

    public List<Map<String, String>> businessCount_achievementNum() {
        String userRealId = null;
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        //只有科研人员和科研管理员能看到此功能
        if ("biz_kyry".equals(currentRoleKey)) { //统计的是自己负责和参与的成果数量
            userRealId = SecurityUtils.getUserRealId();
        }

        List<Map<String, String>> maps = baseMapper.achievementNumCount(userRealId);
        return maps;
    }


}
